/**
 * Created by PanJiaChen on 16/11/18.
 */
import _ from 'lodash';

export default {

  	// var arr = {
  	//   a: ['红', '黄', '蓝', '绿'],
  	//   b: ['大', '中', '小'],
  	//   c: ['A', 'B', 'C', 'D'],
  	//   d: ['高', '矮', '胖', '瘦']
  	// }
  	// console.log(arrange(arr));
  	/**
   	* @priceOption {Object}
   	* Object = {
		a: ['红', '黄', '蓝', '绿'],
		b: ['大', '中', '小'],
		c: ['A', 'B', 'C', 'D'],
		d: ['高', '矮', '胖', '瘦']
		}
	* @returns {Arrer}
	*/
  	arrange(priceOption) {
		var priceFactor = []
		for (const k in priceOption) {
			priceFactor.push(k)
		}

		function plzhFirst(datas) {
			var array = [];
			var propObj = getFirstProp(datas);
			var propName = propObj.name;
			var propValue = propObj.value;
			if (_.isArray(propValue)) {
				for (var i = 0; i < propValue.length; i++) {
					var newObj = {};
					newObj[propName] = propValue[i];
					array.push(newObj);
				}
			} else {
				var newObj = {};
				newObj[propName] = propValue;
				array.push(newObj)
			}
			for (var i = 1; i < priceFactor.length; i++) {
				array = plzh(array, priceOption[priceFactor[i]], priceFactor[i])
			}
			return array
		}

		function getFirstProp(obj) {
			var propObj = {}
			for (var i in obj) {
				propObj.name = i;
				propObj.value = obj[i];
				return propObj;
			}
		}

		function plzh(arr1, arr2, nextAttr) {
			var array = [];
			for (var i = 0; i < arr1.length; i++) {
				var obj = arr1[i];
				for (var j = 0; j < arr2.length; j++) {
					var newObj = _.cloneDeep(obj);
					var v2 = arr2[j];
					newObj[nextAttr] = v2;
					array.push(newObj);
				};
			};
			return array;
		}

		var endData = plzhFirst(priceOption);

		return endData
	},
	// 格式化价格
	prices(n, type = 'except', per = 100) {
		if (!n) return 0
		return type === 'multiply' ? (n * per) : (n / per)
	},
	// base64编码
	encode(str) {
		if (!str) return ''
		return btoa(
			encodeURIComponent(str).replace(
				/%([0-9A-F]{2})/g,
				function toSolidBytes(match, p1) {
					return String.fromCharCode("0x" + p1);
				}
			)
		);
	},
	// base64解码
	decode(str) {
		if (!str) return ''

		if(str.indexOf('{') != -1){
			str = str.substr(0, str.length - 1);
			str = str.substr(1, str.length - 1);
		}
		return decodeURIComponent(
			atob(str)
			.split("")
			.map(function (c) {
				return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
			})
			.join("")
		);
	},
	// 验证手机号
	isphone(e) {
		var msg = /^1[3456789]{1}\d{9}$/
		return msg.test(e)
	},
	// 图片上传前的钩子
	beforeUpload(file) {
		var type = "image/jpg,image/jpeg,image/png,image/gif";
		const isJPG = type.indexOf(file.type) != -1;
		const isLt1M = file.size / 1024 / 1024 < 1;

		if (!isJPG) {
			this.$message.error("上传图片只能是 JPG,JPEG,PNG,GIF 格式!");
		}
		if (!isLt1M) {
			this.$message.error("上传图片大小不能超过 1MB!");
		}
		return isJPG && isLt1M;
	},
	// 控制字符串长度，过长显示...
	controlLength(curStr, len = 12) {
		if (!curStr) return "";
		if (curStr.length > len) return curStr.slice(0, len) + "..."
		return curStr;
	}
}
